package com.kevin.wiki.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author kevin.lv
 * @date 2022/2/25 11:44
 */
public class Tel {


    /**
     * Regular expressions实现手机号去86,+86,+86-，86-
     *
     * @param phoneNum
     * @return
     */
    public static String checkPhoneNum(String phoneNum) {
        String resultTel = "";
        if (phoneNum.contains("-")) {
            Pattern p1 = Pattern.compile("^((\\+{0,2}86-){0,2})1[0-9]{10}");
            Matcher m1 = p1.matcher(phoneNum);
            if (m1.matches()) {
                Pattern p2 = Pattern.compile("^((\\+{0,2}86-){0,2})");
                Matcher m2 = p2.matcher(phoneNum);
                StringBuffer sb = new StringBuffer();
                while (m2.find()) {
                    m2.appendReplacement(sb, "");
                }
                m2.appendTail(sb);
                resultTel = sb.toString();

            }
        } else if (phoneNum.contains(" ")) {
            Pattern p1 = Pattern.compile("^((\\+{0,2}86 ){0,2})1[0-9]{10}");
            Matcher m1 = p1.matcher(phoneNum);
            if (m1.matches()) {
                Pattern p2 = Pattern.compile("^((\\+{0,2}86 ){0,2})");
                Matcher m2 = p2.matcher(phoneNum);
                StringBuffer sb = new StringBuffer();
                while (m2.find()) {
                    m2.appendReplacement(sb, "");
                }
                m2.appendTail(sb);
                resultTel = sb.toString();

            }
        } else if (phoneNum.contains("86")) {
            Pattern p1 = Pattern.compile("^((\\+{0,1}86){0,1})1[0-9]{10}");
            Matcher m1 = p1.matcher(phoneNum);
            if (m1.matches()) {
                Pattern p2 = Pattern.compile("^((\\+{0,1}86){0,1})");
                Matcher m2 = p2.matcher(phoneNum);
                StringBuffer sb = new StringBuffer();
                while (m2.find()) {
                    m2.appendReplacement(sb, "");
                }
                m2.appendTail(sb);
                resultTel = sb.toString();
            }
        } else {
            resultTel = phoneNum;
        }
        if (resultTel.length() <= 0 || resultTel == "") {
            return phoneNum;
        }
        return resultTel;
    }

    public static void main(String[] args) {
        String tel = checkPhoneNum("(417) 831-9362 X 428");
        System.out.println(tel);
    }

}
